package org.jobtask.schedule;

import javax.swing.text.BadLocationException;

import org.jobtask.iface.Scheduling;

public class RepeatJob  implements Scheduling{
	
	private boolean isStop=false;
	private JobTask jobTask=null;
	private TaskFlow taskFlow;
	private Integer count=0;
//	private Integer runCount;
//	private String useTime="00:00:00";
	

	public RepeatJob(JobTask task){
		this.jobTask=task;
		this.taskFlow=new TaskFlow(this.jobTask.getCommand());
	}
	
	@Override
	public void run() {
			while(!isStop){
				if(this.jobTask.getCount()>0){
					this.count++;
					if(this.count>this.jobTask.getCount()){
						this.jobTask.setState(JobState.STOP);
						this.clearCache();
						isStop=true;
						break;
					}
				}
				if(!this.taskFlow.begin()) break;
				if(this.taskFlow.monitor(this.jobTask)){
					try {
						Thread.sleep(jobTask.getInterval()*1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} 
				}else{
					this.jobTask.setState(JobState.STOP);
					this.clearCache();
					break;
				}
		}
	}
	
	@Override
	public void halt(){
			this.taskFlow.destroy();
			this.isStop=true;
			if(this.getJobRunState()){
			   this.jobTask.setState(JobState.STOP);
			}else{
				this.jobTask.setState(JobState.PAUSE);
			}
			Runtime.getRuntime().gc();
	}
	
	private void clearCache(){
		try {
			this.jobTask.clearLog(false);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	
	public boolean getJobRunState(){
		return this.taskFlow.isSeccess();
	}
}
